﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace JMDCMS.Win.Admin
{
    public partial class Site : JMDCMS.Library.Win.WinPartBase, 
        JMDCMS.Library.Interfaces.ISave
    {
        JMDCMS.BusinessObjects.JmdSite _site;
        
        public Site()
        {
            InitializeComponent();
        }

        #region ISave Members

        public void Bind()
        {

            _site = JMDCMS.BusinessObjects.JmdSite.NewJmdSite();
            this.SiteBS.DataSource = _site;
                            
            this.MainBN.BindingSource = this.SiteBS;
        }

        public bool Save()
        {
            RebindUI(true, true);
            return true;
        }

        #endregion


        private void RebindUI(bool saveObject, bool rebind)
        {
            // disable events
            this.SiteBS.RaiseListChangedEvents = false;

            try
            {
                // unbind the UI
                UnbindBindingSource(this.SiteBS, saveObject, true);

                // save or cancel changes
                if (saveObject)
                {
                    _site.ApplyEdit();

                    try
                    {
                        _site = _site.Save();
                    }
                    catch (Csla.DataPortalException ex)
                    {
                        MessageBox.Show(ex.BusinessException.ToString(),
                          "Error saving", MessageBoxButtons.OK,
                          MessageBoxIcon.Exclamation);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(),
                          "Error Saving", MessageBoxButtons.OK,
                          MessageBoxIcon.Exclamation);
                    }
                }
                else
                    _site.CancelEdit();
            }
            finally
            {
                // rebind UI if requested
                if (rebind)
                    BindUI();

                // restore events
                this.SiteBS.RaiseListChangedEvents = true;

                if (rebind)
                {
                    // refresh the UI if rebinding
                    this.SiteBS.ResetBindings(false);
                 }
            }
        }

        private void BindUI()
        {
            _site.BeginEdit();
            this.SiteBS.DataSource = _site;
        }

    }
}
